<template>
	<!-- #ifdef MP-WEIXIN -->
	<root-portal>
	<!-- #endif -->
	<u-popup :show="showCoupon"
						mode="bottom" 
						closeable
						@close="showCoupon = false"
						:customStyle="{'max-height':'1000rpx'}">
		<view class="u-text-center u-p-30">
			<text>选择优惠券</text>
		</view>
		
		<view class="u-p-30">
			<scroll-view scroll-y="true" style="max-height: 840rpx;">
				<u-radio-group placement="column" v-model="selectedShopUserCouponId">
					<view style="min-height: 180rpx;" v-for="(coupon, index) in dataList" :key="index">
						<view class="card u-m-b-30 card-bg">
							<view class="card-left">
								<template v-if="coupon.couponType == '1'">
									<!-- 代金券的场合 -->
									<view>
										<text class="text-bold u-font-44">{{coupon.deductionPrice | formatMoneyToYuanIntFilter}}</text>
										<text class="u-font-26 u-m-l-10 text-bold">元</text>
									</view>
								</template>
								<template v-else>
									<!-- 折扣券 -->
									<view>
										<text class="text-bold u-font-44">{{coupon.discountRate | formatDiscountFilter}}</text>
										<text class="u-font-26 u-m-l-10 text-bold">折</text>
									</view>
								</template>
							</view>
							<view class="card-right">
								<view class="u-line-1">
									<text class="text-bold u-font-32">{{coupon.couponName}}</text>
								</view>
								<view class="card-info text-bold u-m-t-10">
									<template v-if="coupon.couponType == '1'">
										<text>满</text>
										<text>{{coupon.orderPrice | formatMoneyToYuanIntFilter}}</text>
										<text>元减</text>
										<text>{{coupon.deductionPrice | formatMoneyToYuanIntFilter}}</text>
										<text>元</text>
									</template>
									<template v-else>
										<text>满</text>
										<text>{{coupon.orderPrice | formatMoneyToYuanIntFilter}}</text>
										<text>元打</text>
										<text>{{coupon.discountRate | formatDiscountFilter}}</text>
										<text>折</text>
									</template>
									
									<template v-if="coupon.point">
										<text class="u-m-l-10 u-m-r-10">+</text>
										<text>{{coupon.point}}</text>
										<text>积分</text>
									</template>
								</view>
								<view class="card-time">
									<view v-if="coupon.expirationType == '2'">
										<!-- 固定时间段的场合 -->
										<template v-if="coupon.couponCurrentStatus == couponCurrentStatusEnum.inProgress">
											<!-- 进行中的场合 -->
											<text>有效期至</text>
											<text>{{formatDate(coupon.effectiveEndDate)}}</text>
										</template>
										<template v-else-if="coupon.couponCurrentStatus == couponCurrentStatusEnum.notStarted">
											<text>有效期:</text>
											<text>{{formatDate(coupon.effectiveStartDate)}}</text>
											<text>至</text>
											<text>{{formatDate(coupon.effectiveEndDate)}}</text>
										</template>
									</view>
									<!-- 领券后生效的场合 -->
									<view v-else-if="coupon.expirationType == '1'">
										<text>领取后</text>
										<text>{{coupon.effectiveDays}}</text>
										<text>天内有效</text>
									</view>
								</view>
								<view style="position: absolute; right: 20rpx;margin-top: 50rpx;" >
									<u-radio :key="coupon.shopUserCouponId" 
														:name="coupon.shopUserCouponId" 
														activeColor="#000000" 
														:disabled="coupon.disabled"
														@change="handleCheckChange(coupon)"></u-radio>
								</view>
							</view>
						</view>
					</view>
				</u-radio-group>
			</scroll-view>
		</view>
	</u-popup>
	<!-- #ifdef MP-WEIXIN -->
	</root-portal>
	<!-- #endif -->
</template>

<script>
	import {getAvailableCoupon} from '@/api/coupon.js'
	import dayjs from 'dayjs'
	import {couponCurrentStatusEnum} from '@/common/const.js'
	
	export default{
		data(){
			return{
				showCoupon:false,
				couponCurrentStatusEnum,
				dataList:[],
				selectedCoupon:null,
				selectedShopUserCouponId:'',
				isFirst:false
			}
		},
		props:{
			sourceOrderPrice:{
				type: Number,
				default: 0
			}
		},
		watch:{
			sourceOrderPrice(){
				console.log("总金额变化")
				this.formatCouponDisabled()
				this.computedCoupon()
			}
		},
		methods:{
			/**
			 * 初始化
			 */
			init(){
				// 获取优惠券列表
				getAvailableCoupon().then(res=>{
					// 获取进行中的优惠券
					let items = res.data.filter(p=>p.couponCurrentStatus == couponCurrentStatusEnum.inProgress)
					// 存在可用优惠券的场合
					if(items.length > 0){
						items.forEach(item=>{
							this.$set(item, 'disabled', false)
						})
						this.dataList = items
						this.formatCouponDisabled()
						this.computedCoupon()
					}
				})
			},
			
			/**
			 * 显示优惠券
			 */
			show(){
				this.showCoupon = true
			},
			
			/**
			 * 格式化优惠券可用
			 */
			formatCouponDisabled(){
				if(this.dataList.length <= 0)
					return;
				
				this.dataList.forEach(item=>{
					if(item.orderPrice > this.sourceOrderPrice){
						item.sort = 0
						item.disabled = true
					} else {
						item.sort = 1
						item.disabled = false
					}
				})
				
				if(this.selectedCoupon && this.selectedCoupon.orderPrice < this.sourceOrderPrice){
					this.selectedCoupon = null
					this.selectedShopUserCouponId = ''
				}
			},
			
			/**
			 * 计算优惠券
			 */
			computedCoupon(){
				if(this.dataList.length <= 0)
					return
				
				// 添加checked属性
				let array = []
				let data = this.dataList.filter(p=>!p.disabled)
				data.forEach(item=>{
					array.push(item.orderPrice)
				})
				debugger
				if(array.length > 0){
					// 找到最大优惠的优惠券
					let minPoint = this.findNearestNumber(array, this.sourceOrderPrice)
					let items = data.filter(p=>p.orderPrice === minPoint)
					if(items.length > 0){
						items[0].sort = 2
						this.selectedCoupon = items[0]
						this.selectedShopUserCouponId = this.selectedCoupon.shopUserCouponId
						this.getDiscountAmount()
					}
					
					this.dataList.sort((a,b)=>{
						return b.sort - a.sort
					})
					this.$emit('selectedCouponCompleted', this.selectedCoupon)
				}
			},
			
			/**
			 * 获取最接近价格的优惠券
			 */
			findNearestNumber(arr, target) {
				return arr.reduce((pre, curr) => {
					return Math.abs(pre - target) > Math.abs(curr - target) ? curr : pre;
				})
			},
			
			/**
			 * 计算折扣金额
			 */
			getDiscountAmount(){
				if(this.selectedCoupon){
					if(this.selectedCoupon.couponType == '1'){
						// 代金券的场合
						this.selectedCoupon.discountAmount = this.selectedCoupon.deductionPrice
					} else if(this.selectedCoupon.couponType == '2'){
						// 折扣券的场合
						this.selectedCoupon.discountAmount = (this.sourceOrderPrice) * (1 - this.selectedCoupon.discountRate / 1000).toFixed(2)
					}
				}
			},
			
			/**
			 * 单选
			 */
			handleCheckChange(coupon){
				this.selectedCoupon = coupon
				//this.selectedCouponId = this.selectedCoupon.id
				this.getDiscountAmount()
				this.$emit('selectedCouponCompleted', this.selectedCoupon)
			},
			
			/**
			 * 格式化优惠券时间
			 */
			formatDate(val){
				return dayjs(val).format('YYYY-MM-DD')
			},
		}
	}
</script>


<style lang="scss" scoped>
	.card{
	  display: flex;
	  align-items: center;
	  width: 100%;
	  padding: 10px 0;
	  background: #fff;
	  border-radius: 8px;
	  -webkit-mask-image: radial-gradient(circle at 88px 4px, transparent 4px, red 4.5px),radial-gradient(closest-side circle at 50%, red 99%, transparent 100%);
	  -webkit-mask-size: 100%, 2px 4px;
	  -webkit-mask-repeat: repeat, repeat-y;
	  -webkit-mask-position: 0 -4px, 87px;
	  -webkit-mask-composite: source-out;
	  mask-composite: subtract;
	  //background: linear-gradient(45deg, orange, red);
	}
	
	.card-bg{
		background: linear-gradient(45deg, #FFB143, #FFECBF);
	}
	
	.card-obtain-bg{
		background: linear-gradient(45deg, #AAAAAA, #FFFFFF);
	}
	
	.card-left{
	  width: 88px;
	  text-align: center;
	  font-size: 18px;
	  color: #000;
	}
	.card-right{
	  padding: 6px 12px;
	  display: flex;
	  flex: 1;
	  flex-direction: column;
	}
	.card-info{
	  margin: 0;
	  font-size: 14px;
	  line-height: 20px;
	  color:#000;
	}
	.card-time{
	  font-size: 12px;
	  line-height: 16px;
	  font-weight: normal;
	  color: #000;
	  margin-top: 4px;
	}
</style>